<template>
  <div class="admin-users">
    <div class="container">
      <h1 class="page-title">用户管理</h1>
      
      <div class="admin-actions">
        <el-input
          placeholder="搜索用户..."
          v-model="searchQuery"
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
        />
      </div>

      <el-card class="users-table-card" v-loading="loading">
        <el-table
          :data="filteredUsers"
          style="width: 100%"
          border
          stripe
          :default-sort="{ prop: 'created_at', order: 'descending' }"
        >
          <el-table-column prop="id" label="ID" width="70" sortable />
          
          <el-table-column prop="username" label="用户名" sortable>
            <template #default="scope">
              <div class="user-info">
                <el-avatar :size="32" icon="el-icon-user"></el-avatar>
                <span>{{ scope.row.username }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="email" label="邮箱" sortable />
          
          <el-table-column prop="full_name" label="姓名" sortable />
          
          <el-table-column prop="phone" label="电话">
            <template #default="scope">
              {{ scope.row.phone || '未设置' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="is_admin" label="角色" width="100">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.is_admin">管理员</el-tag>
              <el-tag type="info" v-else>普通用户</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="注册时间" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button 
                type="primary" 
                icon="el-icon-edit" 
                size="small" 
                circle
                @click="handleEditUser(scope.row)"
              />
              
              <el-button 
                :type="scope.row.is_admin ? 'danger' : 'success'" 
                :icon="scope.row.is_admin ? 'el-icon-close' : 'el-icon-check'" 
                size="small" 
                circle
                @click="toggleAdminStatus(scope.row)"
                :disabled="scope.row.id === currentUser.id"
              />
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalUsers"
            :page-size="10"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户信息"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="editingUser" label-width="100px" v-if="editingUser">
        <el-form-item label="用户名">
          <el-input v-model="editingUser.username" disabled />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input v-model="editingUser.email" />
        </el-form-item>
        
        <el-form-item label="姓名">
          <el-input v-model="editingUser.full_name" />
        </el-form-item>
        
        <el-form-item label="电话">
          <el-input v-model="editingUser.phone" />
        </el-form-item>
        
        <el-form-item label="地址">
          <el-input 
            type="textarea" 
            v-model="editingUser.address" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser" :loading="updating">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useStore } from 'vuex';

export default {
  name: 'AdminUsers',
  setup() {
    const store = useStore();
    const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
    
    // 状态
    const users = ref([]);
    const loading = ref(false);
    const searchQuery = ref('');
    const currentPage = ref(1);
    const dialogVisible = ref(false);
    const editingUser = ref(null);
    const updating = ref(false);
    
    // 获取当前用户
    const currentUser = computed(() => store.getters['auth/currentUser']);
    
    // 获取认证头
    const authHeader = computed(() => store.getters['auth/authHeader']);
    
    // 筛选后的用户
    const filteredUsers = computed(() => {
      if (!searchQuery.value) {
        return users.value;
      }
      
      const query = searchQuery.value.toLowerCase();
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query) ||
        user.full_name.toLowerCase().includes(query) ||
        (user.phone && user.phone.includes(query))
      );
    });
    
    const totalUsers = computed(() => filteredUsers.value.length);
    
    // 加载所有用户
    const loadUsers = async () => {
      loading.value = true;
      try {
        const response = await axios.get(`${API_URL}/users`, { 
          headers: authHeader.value
        });
        users.value = response.data;
      } catch (error) {
        const errorMessage = error.response?.data?.message || '加载用户数据失败';
        ElMessage.error(errorMessage);
      } finally {
        loading.value = false;
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      const options = { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      };
      return new Date(dateString).toLocaleDateString('zh-CN', options);
    };
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 编辑用户
    const handleEditUser = (user) => {
      editingUser.value = { ...user };
      dialogVisible.value = true;
    };
    
    // 更新用户信息
    const updateUser = async () => {
      updating.value = true;
      try {
        // 调用API更新用户信息
        const response = await axios.put(`${API_URL}/users/${editingUser.value.id}`, {
          email: editingUser.value.email,
          full_name: editingUser.value.full_name,
          phone: editingUser.value.phone,
          address: editingUser.value.address
        }, {
          headers: authHeader.value
        });
        
        // 更新本地用户列表
        const index = users.value.findIndex(u => u.id === editingUser.value.id);
        if (index !== -1) {
          users.value[index] = response.data;
        }
        
        dialogVisible.value = false;
        ElMessage.success('用户信息已更新');
      } catch (error) {
        const errorMessage = error.response?.data?.message || '更新用户信息失败';
        ElMessage.error(errorMessage);
      } finally {
        updating.value = false;
      }
    };
    
    // 切换管理员状态
    const toggleAdminStatus = async (user) => {
      // 防止修改自己的管理员状态
      if (user.id === currentUser.value.id) {
        ElMessage.warning('不能修改自己的管理员状态');
        return;
      }
      
      const action = user.is_admin ? '移除' : '设置为';
      const confirmMessage = `确定要${action}管理员权限吗？`;
      
      try {
        await ElMessageBox.confirm(confirmMessage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 调用API更新用户的管理员状态
        const response = await axios.put(`${API_URL}/users/${user.id}/admin`, {
          is_admin: !user.is_admin
        }, {
          headers: authHeader.value
        });
        
        // 如果服务器返回了更新后的用户对象，则使用它
        if (response.data.user) {
          const index = users.value.findIndex(u => u.id === user.id);
          if (index !== -1) {
            users.value[index] = response.data.user;
          }
        } else {
          // 否则仅更新管理员状态
          const index = users.value.findIndex(u => u.id === user.id);
          if (index !== -1) {
            users.value[index].is_admin = !user.is_admin;
          }
        }
        
        ElMessage.success(`已${action}管理员权限`);
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = error.response?.data?.message || '操作失败';
          ElMessage.error(errorMessage);
        }
      }
    };
    
    // 组件挂载时加载用户数据
    onMounted(() => {
      loadUsers();
    });
    
    return {
      users,
      filteredUsers,
      loading,
      searchQuery,
      currentPage,
      totalUsers,
      dialogVisible,
      editingUser,
      updating,
      currentUser,
      formatDate,
      handlePageChange,
      handleEditUser,
      updateUser,
      toggleAdminStatus
    };
  }
}
</script>

<style lang="scss" scoped>
.admin-users {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.admin-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .search-input {
    width: 300px;
  }
}

.users-table-card {
  margin-bottom: 30px;
}

.user-info {
  display: flex;
  align-items: center;
  
  .el-avatar {
    margin-right: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 